package com.aiyige.page.my.customer;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.CustomerListFilter;
import com.aiyige.model.Subject;
import com.aiyige.model.request.GetCustomerFilterRequest;
import com.aiyige.model.response.CustomerScreenFilterResponse;
import com.aiyige.page.detail.decoration.MyRecyclerViewDivider;
import com.aiyige.page.my.customer.adapter.CustomerScreenLeftAdapter;
import com.aiyige.page.my.customer.adapter.CustomerScreenRightAdapter;
import com.aiyige.page.my.customer.adapter.CustomerScreenTopAdapter;
import com.aiyige.page.my.customer.callback.ScreenCallback;
import com.aiyige.page.my.customer.model.CustomerScreenChildEntity;
import com.aiyige.page.my.customer.model.CustomerScreenFatherEntity;
import com.aiyige.page.publish.majorcourse.PublishMajorCourseFormPage;
import com.aiyige.page.publish.majorcourse.model.MajorCourseType;
import com.aiyige.setup.model.Setup;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.track.annotation.Track;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.MyLayoutManager;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 客户管理筛选
 * Created by xiachao on 2018/3/26.
 */
@Track("客户管理")
@Route(path = ARouterConfig.CustomerScreenPage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class CustomerScreenPage extends BaseActivity implements ScreenCallback {

    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.recyclerViewTop)
    RecyclerView recyclerViewTop;
    @BindView(R.id.recyclerViewLeft)
    RecyclerView recyclerViewLeft;
    @BindView(R.id.recyclerViewRight)
    RecyclerView recyclerViewRight;


    CustomerScreenLeftAdapter leftAdapter;
    CustomerScreenRightAdapter rightAdapter;
    CustomerScreenTopAdapter topAdapter;

    List<CustomerScreenChildEntity> topList = new ArrayList<>();
    List<CustomerScreenFatherEntity> leftList = new ArrayList<>();
    List<CustomerScreenChildEntity> rightList = new ArrayList<>();

    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.btn_reset)
    Button btnReset;
    @BindView(R.id.btn_finish)
    Button btnFinish;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;

    @BindView(R.id.rl_top)
    RelativeLayout rlTop;

    HandlerThread handlerThread;
    Handler requestDataHandler;

    private final static int MSG_WORK = 0x01;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_customer_screen);
        ButterKnife.bind(this);
//        ARouter.getInstance().inject(this);
        if (getIntent().getParcelableArrayListExtra("topList") != null) {
            topList = getIntent().getParcelableArrayListExtra("topList");
        }
        if (handlerThread == null) {
            handlerThread = new HandlerThread("requestList");
        }
        handlerThread.start();
        requestDataHandler = new Handler(handlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                doRequest();
            }
        };
//        testData();
        initView();
        initData();
    }


    private void initView() {
        topAdapter = new CustomerScreenTopAdapter();
        topAdapter.setCallback(this);
        leftAdapter = new CustomerScreenLeftAdapter();
        leftAdapter.setCallback(this);
        rightAdapter = new CustomerScreenRightAdapter();
        rightAdapter.setCallback(this);
        MyLayoutManager linearLayoutManagerTop = new MyLayoutManager();
        linearLayoutManagerTop.setAutoMeasureEnabled(true);
        LinearLayoutManager linearLayoutManagerLeft = new LinearLayoutManager(this);
        LinearLayoutManager linearLayoutManagerRight = new LinearLayoutManager(this);
        recyclerViewTop.setLayoutManager(linearLayoutManagerTop);
        recyclerViewLeft.setLayoutManager(linearLayoutManagerLeft);
        recyclerViewRight.setLayoutManager(linearLayoutManagerRight);
//        recyclerViewTop.addItemDecoration(new MyRecyclerViewDivider(
//                this, LinearLayoutManager.VERTICAL, UIHelper.dip2px(this, 5), ContextCompat.getColor(this,R.color.transparent)));
        recyclerViewRight.addItemDecoration(new MyRecyclerViewDivider(
                this, LinearLayoutManager.VERTICAL, UIHelper.dip2px(this, 10), R.color.white));
        recyclerViewTop.setAdapter(topAdapter);
        recyclerViewLeft.setAdapter(leftAdapter);
        recyclerViewRight.setAdapter(rightAdapter);
    }

    private void doRequest() {
        final CustomerScreenFatherEntity currentEntity = getCurrentEntity();
        if (currentEntity == null) {
            return;
        }
        rightList.clear();
        rightAdapter.notifyDataSetChanged();
        currentEntity.setSubject(Subject.major_course);
        GetCustomerFilterRequest.newBuilder().subject(currentEntity.getSubject()).tagId(currentEntity.getId()).build().enqueue(new Callback<ResponseBody>() {

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    try {
                        String json = response.body().string();
                        Log.v("", json);
                        CustomerScreenFilterResponse filterResponse = JsonUtil.toObject(json, CustomerScreenFilterResponse.class);

                        if (filterResponse != null && !ListUtil.isEmpty(filterResponse.getContent())) {
                            for (CustomerListFilter customerListFilter : filterResponse.getContent()) {
                                if (!isNull(customerListFilter.getSubject()) && currentEntity.getSubject().equals(customerListFilter.getSubject())) {
                                    // 遍历出所有数据转换到自己的view中
//                                    for (CustomerListFilterTag tag : customerListFilter.getTags()) {
//                                        rightList.add(CustomerScreenChildEntity.newBuilder().id(tag.getId()).name(tag.getName()).build());
//                                    }
                                    rightList.add(CustomerScreenChildEntity.newBuilder().id(customerListFilter.getId()).name(customerListFilter.getTitle()).build());
                                }
                            }
                            if (!ListUtil.isEmpty(rightList)) {
                                setSelectedList(rightList);
                                rightAdapter.setNewData(rightList);
                            }
                        }
//
                    } catch (IOException e) {

                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });


    }

    private void initData() {
        topAdapter.setNewData(topList);
        if (!ListUtil.isEmpty(topList)) {// 把已选择的列表带入新页面
            for (CustomerScreenChildEntity topEntity : topList) {
                for (CustomerScreenChildEntity rightEntity : rightList) {
                    if (rightEntity.getId().equals(topEntity.getId())) {
                        rightEntity.setSelected(true);
                    }
                }
            }
        }
        notifyTopList();
//         customerScreenEntity = new CustomerScreenFatherEntity();
////        customerScreenEntity.setName(getString(R.string.training_class));
////        customerScreenEntity.setSelected(true);
////        customerScreenEntity.setId("training_course");
////        leftList.add(customerScreenEntity);
//
//        customerScreenEntity = new CustomerScreenFatherEntity();
//        customerScreenEntity.setName(getString(R.string.major_course));
//        customerScreenEntity.setSelected(true);
//        customerScreenEntity.setId("major_course");
//        leftList.add(customerScreenEntity);

        new RequestMajorCourseTypeAsyncTask().execute();
//        rightAdapter.setNewData(rightList);
//        leftAdapter.setNewData(leftList);
//        requestDataHandler.removeMessages(MSG_WORK);
//        requestDataHandler.sendEmptyMessage(MSG_WORK);
    }

    private CustomerScreenFatherEntity getCurrentEntity() {
        for (CustomerScreenFatherEntity entity : leftList) {
            if (entity.isSelected()) {
                return entity;
            }
        }
        return null;
    }
//
//    private void testData() {
//        CustomerScreenChildEntity customerScreenEntity;
////        for (int i = 0; i < 2; i++) {
////            customerScreenEntity = new CustomerScreenEntity();
////            customerScreenEntity.setName("所属班级" + i);
////            customerScreenEntity.setSelected(i == 0);
////            customerScreenEntity.setId(i + "");
////            leftList.add(customerScreenEntity);
////        }
//
//
//        for (int i = 0; i < 20; i++) {
//            customerScreenEntity = new CustomerScreenChildEntity();
//            customerScreenEntity.setName(i % 2 == 0 ? "爵士舞少儿暑期集训南京夏令营" + i : "小天鹅舞蹈成人版" + i);
//            customerScreenEntity.setId(i + "");
//            rightList.add(customerScreenEntity);
//        }
//
//    }

    private void rightNotifyData() {
        for (CustomerScreenFatherEntity entity : leftList) {
            if (entity.isSelected()) {
                if (ListUtil.isEmpty(entity.getList())) {
                    requestDataHandler.removeMessages(MSG_WORK);
                    requestDataHandler.sendEmptyMessage(MSG_WORK);
                } else {
                    setSelectedList(entity.getList());
                    rightAdapter.setNewData(entity.getList());
                }
            }
        }
    }

    private void setSelectedList(List<CustomerScreenChildEntity> list) {
        if (!ListUtil.isEmpty(topList) && !ListUtil.isEmpty(list)) {
            for (CustomerScreenChildEntity topEntity : topList) {
                for (CustomerScreenChildEntity entity : list) {
                    if (!isEmpty(topEntity.getId()) && !isEmpty(entity.getId())
                            && topEntity.getId().equals(entity.getId())) {
                        entity.setSelected(true);
                    }
                }
            }
        }
    }


    @Override
    public void onRightClick(CustomerScreenChildEntity entity) {
        entity.setSelected(true);//右侧选中
        rightAdapter.notifyDataSetChanged();
        topList.add(entity);//top添加
        topAdapter.setNewData(topList);
        notifyTopList();
    }

    @Override
    public void onRightDelete(CustomerScreenChildEntity entity) {
        topDelete(entity);//top删除
        entity.setSelected(false);//右侧非选中
        rightAdapter.notifyDataSetChanged();
    }

    @Override
    public void onTopDelete(CustomerScreenChildEntity entity) {
        topDelete(entity);//top删除
        entity.setSelected(false);//右侧非选中
        rightAdapter.unSelect(entity);
    }

    @Override
    public void onLeftClick(CustomerScreenFatherEntity entity) {
        for (CustomerScreenFatherEntity leftCustomer : leftList) {
            leftCustomer.setSelected(entity.getId().equals(leftCustomer.getId()));
        }
        leftAdapter.notifyDataSetChanged();
        // 后面
        rightNotifyData();
    }

    private void topDelete(CustomerScreenChildEntity entity) {
        for (CustomerScreenChildEntity topCustomer : topList) {
            if (topCustomer.getId().equals(entity.getId())) {
                topList.remove(topCustomer);
                break;
            }
        }
        notifyTopList();
    }

    private void reset() {
        topList.clear();
        notifyTopList();
        for (CustomerScreenChildEntity entity : rightList) {
            entity.setSelected(false);
        }
        rightAdapter.notifyDataSetChanged();

    }

    @OnClick({R.id.titleBackBtn, R.id.btn_reset, R.id.btn_finish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.btn_reset:
                reset();
                break;
            case R.id.btn_finish:
                Intent intent = new Intent();
                intent.putExtra("list", (Serializable) topList);
                setResult(RESULT_OK, intent);
                finish();
                break;
        }
    }


    private void notifyTopList() {
        // 解决无数据的时候由于padding导致有占有空间的问题
        if (ListUtil.isEmpty(topList)) {
            rlTop.setPadding(0, 0, 0, 0);
        } else {
            rlTop.setPadding(UIHelper.dip2px(10), UIHelper.dip2px(10), UIHelper.dip2px(10), UIHelper.dip2px(10));
        }
        if (topAdapter != null) {
            topAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (requestDataHandler != null) {
            requestDataHandler.removeMessages(MSG_WORK);
        }
        if (handlerThread != null) {
            handlerThread.quit();
        }
    }

    public class RequestMajorCourseTypeAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(CustomerScreenPage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().getSetup(SetupUtil.GROUP_TYPE_MAJOR_COURSE_TYPE, BuildConfig.appVersion, "all").execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                List<Setup> setupList = JSON.parseArray(json, Setup.class);
                leftList = new LinkedList<>();
                CustomerScreenFatherEntity customerScreenFatherEntity;
                for (Setup setup : setupList) {
                    customerScreenFatherEntity = new CustomerScreenFatherEntity();
                    customerScreenFatherEntity.setId(setup.getId());
                    customerScreenFatherEntity.setName((String) setup.getData().get("name"));
                    if (leftList.isEmpty()) {
                        customerScreenFatherEntity.setSelected(true);
                    }
                    leftList.add(customerScreenFatherEntity);
                }
                if (ListUtil.isEmpty(leftList)) {
                    throw new Exception(StringUtils.getString(R.string.no_result));
                }
                return leftList;
            } catch (Exception e) {
                leftList = null;
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                try {
                    leftAdapter.setNewData((List<CustomerScreenFatherEntity>)o);
                    requestDataHandler.removeMessages(MSG_WORK);
                    requestDataHandler.sendEmptyMessage(MSG_WORK);
                } catch (Exception e) {

                }

            }
        }
    }

}
